package com.mspbots.teams.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mspbots.api.client.CoreClient;
import com.mspbots.teams.model.Messages;
import com.mspbots.teams.model.MessagesLog;
import com.mspbots.teams.service.MessageService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class MessageConsumer {

    public static final String REDIS_KEY_PREFIX_SYSTEM = "MSPBOTS:CONFIG:SYSTEM:";
    public static final String REDIS_KEY_PREFIX_TENANT = "MSPBOTS:CONFIG:TENANT:";
    public static final String CONFIGURATION_MESSAGE_SWITCH = "message_switch";

    @Autowired
    private MessageService messageService;
    @Autowired
    private CoreClient coreClient;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RabbitMessagingTemplate messagingTemplate;

    @RabbitListener(queues = "teams.message.send")
    public void onMessage(Channel channel, Messages messages, Message message) {
        try {
            boolean sendResult = messageService.sendToTeams(messages);
            if (sendResult) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }

        } catch (Exception e) {
            log.error("message [{}] send error", messages.getId());
            try {

                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    @RabbitListener(queues = "teams.message.sendForward")
    public void onMessageForward(Channel channel, Messages messages, Message message) {
        try {
//            log.debug("send forward : {} {}", messages.getId(), messages.getBusinessId());
            boolean sendResult = messageService.sendToTeamsForward(messages);
            if (sendResult) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }

        } catch (Exception e) {
            log.error("message [{}] send forward error", messages.getId());
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @RabbitListener(queues = "teams.message.send.log")
    public void onMessage(MessagesLog messagesLog) {
        coreClient.post("messages-log", messagesLog).subscribe();
    }

    /*@Scheduled(fixedRate = 30 * 1000)
    public void test() {
        Map<String,Object> params = Map.of("tenantId",1);
        JsonNode result = coreClient.get("/teams/messages/list/send", params).block();
                List<Messages> savedMessage = this.objectMapper.convertValue(result, new TypeReference<>() {
                });
        savedMessage.forEach(item -> messagingTemplate.convertAndSend("msp.message.teams", "", item));
    }*/


}
